package ua.kharkiv.khpi.tarasenko.diploma;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import java.util.Map;

public class Demo {

	private static PseudoDB getDBFromFile(File input) throws IOException {
		PseudoDB db = new PseudoDB();

		BufferedReader reader = new BufferedReader(new FileReader(input));

		Pattern row = Pattern.compile("(\\d+)\\|(\\d+)\\|(\\d+)");
		String inputRow = "";
		Matcher m = null;
		String lastTransId = "";
		String currentTransId = "";

		Sequence curSeq = new Sequence();

		while ((inputRow = reader.readLine()) != null) {
			m = row.matcher(inputRow);
			if (m.find()) {
				String transId = m.group(1);
				String itemId = m.group(2);
				String actionId = m.group(3);

				currentTransId = transId;
				if (!currentTransId.equals(lastTransId)) {
					db.addRow(curSeq);
					curSeq = new Sequence();
				}
				Item item = Item.getItem(itemId);
				item.setUserAction(UserAction.getUSerActionById(Integer.parseInt(actionId)));
				curSeq.addItem(item);

				lastTransId = currentTransId;
			}
		}

		reader.close();
		return db;
	}

	private static void writeToFile(Map<Sequence, Integer> freqSeqs, File output)
			throws IOException {
		BufferedWriter writer = new BufferedWriter(new FileWriter(output));
		for (Map.Entry<Sequence, Integer> entry : freqSeqs.entrySet()) {
			writer.append(entry.getKey() + "	:	" + entry.getValue());
			writer.newLine();
		}
		writer.close();
	}

	private static PseudoDB getDBWhithPurchases (PseudoDB generalDB) {
		PseudoDB purchasesDB = new PseudoDB();
		
		for (Sequence seq : generalDB.getRows()) {
			boolean containsPurchase = false;
			for (Item item : seq.getItems()) {
				if (item.getUserAction().equals(UserAction.PURCHASE)) {
					containsPurchase = true;
					break;
				}
			}
			if (containsPurchase) {
				purchasesDB.addRow(seq);
			}
		}
		
		return purchasesDB;
	}
	
	public static void main(String[] args) throws IOException {

		File input = new File("[test]transact_train.txt");
		File output = new File("trans_train.txt");
		// if (output.exists()) {
		// output.delete();
		// }
		//
		// new FileTransform(input, output).transform();

		int min_sup = 2;
		//
		PseudoDB db = getDBFromFile(input);
		PseudoDB dbWithPurchase = getDBWhithPurchases(db);
		System.out.println("downloaded. " + new Date());
		
		long timeStart = System.currentTimeMillis();
//		Analysator an = new Analysator(min_sup, db);
		GeneralAnalysis an = new GeneralAnalysis();
		Map<Sequence, Integer> freqSeqs = an.analyze(dbWithPurchase, min_sup);
		long timeFinish = System.currentTimeMillis();
		writeToFile(freqSeqs, output);

		System.out.println("It took: "
				+ ((timeFinish - timeStart) / (1000 * 60)) + "mins");
	}
}
